
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>持久化与消息可靠性 - 交互式测验</title>
      <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap');
        
        body {
          font-family: 'Noto Sans SC', sans-serif;
          background-color: #f4f7f9;
          color: #333;
          display: flex;
          justify-content: center;
          align-items: center;
          min-height: 100vh;
          margin: 0;
          padding: 20px;
          box-sizing: border-box;
        }
        
        .main-wrapper {
            position: relative;
            width: 100%;
            max-width: 900px; /* Wider to accommodate buttons */
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .quiz-container {
          background-color: #ffffff;
          border-radius: 16px;
          box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
          width: 100%;
          max-width: 700px;
          overflow: hidden;
          z-index: 10;
        }

        .quiz-header {
          background-color: #4a90e2;
          color: white;
          padding: 20px 30px;
          text-align: center;
        }

        .quiz-header h1 {
          margin: 0;
          font-size: 24px;
          font-weight: 700;
        }
        
        .quiz-header p {
            margin: 5px 0 0;
            font-size: 14px;
            opacity: 0.9;
        }

        .quiz-body {
          padding: 30px;
        }

        .progress-bar {
            display: none; /* 隐藏进度条 */
            width: 100%;
            background-color: #e0e0e0;
            border-radius: 5px;
            height: 10px;
            margin-bottom: 20px;
        }

        #progress-indicator {
            height: 100%;
            width: 0%;
            background-color: #4caf50;
            border-radius: 5px;
            transition: width 0.3s ease;
        }

        #question-container {
          margin-bottom: 20px;
        }

        #question-text {
          font-size: 18px;
          font-weight: 500;
          line-height: 1.6;
          margin-bottom: 25px;
        }

        .options-list {
          list-style: none;
          padding: 0;
          margin: 0;
        }

        .option-item {
          background-color: #f8f9fa;
          border: 1px solid #dee2e6;
          border-radius: 8px;
          padding: 15px;
          margin-bottom: 12px;
          cursor: pointer;
          transition: background-color 0.2s ease, border-color 0.2s ease;
        }

        .option-item:hover {
          background-color: #e9ecef;
        }
        
        .option-item.selected {
            background-color: #d1e7fd;
            border-color: #4a90e2;
        }

        .quiz-footer {
          padding: 20px 30px;
          display: flex;
          justify-content: space-between; /* 将按钮分布在两侧 */
          align-items: center;
          min-height: 65px; /* Reserve space */
        }

        .nav-btn {
          background-color: #4a90e2;
          color: white;
          border: none;
          border-radius: 8px;
          padding: 10px 20px;
          font-size: 16px;
          font-weight: 500;
          cursor: pointer;
          transition: background-color 0.2s ease, transform 0.2s ease;
          box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        #next-btn {
            background-color: #28a745;
        }

        .nav-btn:hover {
          background-color: #357abd;
          transform: scale(1.05);
        }
        
        .nav-btn:disabled {
            background-color: #a0c3e8;
            cursor: not-allowed;
            opacity: 0.7;
        }

        #result-container {
            border-top: 1px solid #eee;
        }
        
        .result-box {
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
        }
        
        .result-box.correct {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .result-box.incorrect {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        
        .result-box h3 {
            margin-top: 0;
        }

        .explanation-text {
            margin-top: 15px;
            line-height: 1.7;
        }
        
        .source-text {
            font-style: italic;
            font-size: 14px;
            margin-top: 15px;
            color: #555;
        }

        
        .final-score-container {
            padding: 40px;
            text-align: center;
        }
        .final-score-container h2 {
            margin-top: 0;
            margin-bottom: 30px;
        }
        .score-summary {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-bottom: 40px;
            flex-wrap: wrap;
        }
        .score-card {
            background-color: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            width: 180px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            border: 1px solid #e9ecef;
        }
        .score-card h3 {
            margin: 0 0 10px;
            font-size: 16px;
            font-weight: 500;
            color: #555;
        }
        .score-card p {
            margin: 0;
            font-size: 28px;
            font-weight: 700;
            color: #333;
        }
        .score-details table {
            width: 100%;
            font-size: 16px;
        }
        .score-details td {
            padding: 4px 0;
        }
        .score-details td:last-child {
            text-align: right;
            font-weight: 700;
        }
        .report-actions button {
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 8px;
            padding: 12px 25px;
            font-size: 16px;
            cursor: pointer;
            margin: 0 10px;
            transition: background-color 0.2s ease, border-color 0.2s ease, transform 0.2s ease;
        }
        .report-actions button:hover {
            background-color: #f1f1f1;
            border-color: #bbb;
            transform: translateY(-2px);
        }
        .report-actions button.primary {
            background-color: #28a745;
            color: white;
            border-color: #28a745;
        }
        .report-actions button.primary:hover {
            background-color: #218838;
        }
        
        .hint-container {
            background-color: #e0f7fa;
            border: 1px solid #b2ebf2;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
            color: #006064;
            font-size: 15px;
            line-height: 1.6;
            display: none; /* 默认隐藏 */
        }
      </style>
    </head>
    <body>
      <div class="main-wrapper">
          <div class="quiz-container">
            <div class="quiz-header">
              <h1>持久化与消息可靠性 - 交互式测验</h1>
              <p>检验你对文档内容的理解程度</p>
            </div>
            <div id="quiz-content">
                <div class="quiz-body">
                    <div class="progress-bar">
                        <div id="progress-indicator"></div>
                    </div>
                    <div id="question-container">
                      <p id="question-text"></p>
                      <ul class="options-list" id="options-list"></ul>
                    </div>
                    <div id="result-container"></div>
                    <div id="hint-container" class="hint-container"></div>
                </div>
                <div class="quiz-footer" id="quiz-footer">
                  <button id="prev-btn" class="nav-btn">上一题</button>
                  <button id="hint-btn" class="nav-btn" style="background-color: #ffc107; color: #333; box-shadow: 0 4px 12px rgba(255,193,7,0.3);">提示</button>
                  <button id="next-btn" class="nav-btn">下一题</button>
                </div>
            </div>
          </div>
      </div>

      <script>
        const quizData = [
  {
    "question": "在RabbitMQ中，为了确保即使在服务器崩溃并重启后消息也不会丢失，最全面的做法是什么？",
    "options": [
      "仅将队列设置为持久化。",
      "启用生产者确认（Publisher Confirms）机制。",
      "将队列和消息都设置为持久化。",
      "仅将消息设置为持久化。"
    ],
    "correctAnswerIndex": 2,
    "explanation": "为了确保消息在服务器重启后不丢失，必须同时满足两个条件：1. 队列本身必须是持久化的（durable=true），这样队列的元数据才能在重启后恢复。2. 消息本身也必须是持久化的（deliveryMode=2），这样消息内容才会被写入磁盘。只满足其中一个条件都无法保证消息在服务器故障后的完全安全。",
    "source": "文档中「RabbitMQ消息持久化」部分的「2 队列持久化」和「3 消息持久化」",
    "hint": "文档提到：“在 RabbitMQ 中，消息和队列可以分别进行持久化配置。”"
  },
  {
    "question": "当消费者使用手动确认模式（Manual Acknowledgment）时，其主要目的是什么？",
    "options": [
      "为了通知生产者消息已成功发送到交换机。",
      "确保消息在被消费者成功处理后才从队列中移除，防止因消费者故障导致消息丢失。",
      "在消息一送达消费者时就自动将其从队列中删除，以提高性能。",
      "保证多条消息能够严格按照发送顺序被消费。"
    ],
    "correctAnswerIndex": 1,
    "explanation": "手动确认机制（Manual Acknowledgment）的核心作用是保证消息处理的可靠性。在这种模式下，RabbitMQ会将消息标记为“未确认”状态并等待消费者的回执。只有当消费者显式调用`basicAck`确认消息已成功处理后，RabbitMQ才会将该消息从队列中彻底删除。如果消费者在处理过程中崩溃或失败，未被确认的消息会重新变为可投递状态，交由其他消费者处理，从而避免了消息丢失。",
    "source": "文档中「RabbitMQ消息可靠性」部分的「2 消息确认与应答机制」",
    "hint": "文档中描述：“RabbitMQ 支持消费者确认模式，确保消息被消费者正确处理后才从队列中移除。”"
  },
  {
    "question": "根据文档，镜像队列（Mirrored Queues）是如何实现高可用性的？",
    "options": [
      "它将消息同时写入多个独立的RabbitMQ集群。",
      "它只在主节点存储消息，但在其他节点保留队列的元数据备份。",
      "如果持有主队列的节点发生故障，系统会自动将一个镜像队列提升为新的主队列，从而保证服务的连续性。",
      "它通过网络分区策略，在网络中断时暂停所有消息处理。"
    ],
    "correctAnswerIndex": 2,
    "explanation": "镜像队列机制通过在集群内的多个节点上创建队列的完整副本（镜像）来提供高可用性。每个镜像队列有一个主队列（Master）和若干个镜像队列（Mirrors）。所有操作首先在主队列上执行，然后同步到所有镜像。当持有主队列的节点失效时，RabbitMQ会自动从存活的镜像中选举一个新的主队列，客户端可以无缝地继续与队列交互，从而实现了故障转移和高可用。",
    "source": "文档中「RabbitMQ的高可用性与容错性」部分的「2 镜像队列（Mirrored Queues）」",
    "hint": "文档关键描述：“如果主队列所在的节点发生故障，系统会自动将镜像队列中的一个节点提升为新的主队列，从而保证消息的可用性。”"
  },
  {
    "question": "在什么情况下，一条消息最有可能被路由到死信队列（Dead Letter Queue, DLQ）？",
    "options": [
      "消息被发布到了一个Fanout类型的交换机。",
      "消费者成功处理了消息并发送了`basicAck`确认。",
      "生产者收到了来自Broker的发布确认（Publisher Confirm）。",
      "消息在队列中等待消费的时间超过了其设置的TTL（Time-To-Live）。"
    ],
    "correctAnswerIndex": 3,
    "explanation": "文档中明确指出了导致消息进入死信队列的几种常见场景。其中之一就是“消息过期”。当一条消息被设置了TTL（存活时间），并且在队列中停留的时间超过了这个阈值而未被消费时，它就会被视为一条“死信”，并被自动转发到配置好的死信交换机和队列中。",
    "source": "文档中「RabbitMQ消息可靠性」部分的「3 消息重试与死信队列（DLQ）」",
    "hint": "思考一下死信队列的应用场景，文档中提到了三个主要原因，其中一个与时间有关。"
  },
  {
    "question": "在对RabbitMQ进行性能优化时，配置消费者的预取计数（Prefetch Count / `basic.qos`）有什么作用？",
    "options": [
      "设置队列可以存储的消息总数上限。",
      "定义消息在队列中的最长存活时间。",
      "限制消费者一次性从队列中获取并处理的未确认消息数量，用于流量控制和负载均衡。",
      "保证生产者发送的每条消息都必须得到确认。"
    ],
    "correctAnswerIndex": 2,
    "explanation": "预取计数（`basic.qos`）是一种重要的消费者端流量控制机制。它告诉RabbitMQ一次最多向该消费者发送多少条未确认（unacked）的消息。通过设置一个合理的预取值，可以防止速度较慢的消费者被大量消息淹没，同时也能让多余的消息被其他空闲的消费者及时处理，从而在多个消费者之间实现更有效的负载均衡，提高整个系统的吞吐量。",
    "source": "文档中「RabbitMQ的性能优化与持久化策略」部分的「1.3 减少队列的阻塞」",
    "hint": "这个配置项用于控制消费者，避免其一次性接收过多来不及处理的消息。"
  },
  {
    "question": "以下哪种RabbitMQ交换机（Exchange）类型会将消息路由到所有与之绑定的队列，而忽略路由键（Routing Key）？",
    "options": [
      "Direct Exchange",
      "Topic Exchange",
      "Fanout Exchange",
      "Headers Exchange"
    ],
    "correctAnswerIndex": 2,
    "explanation": "Fanout（扇出）交换机的工作模式非常简单，它会无条件地将接收到的任何消息广播给所有绑定到它的队列。它完全忽略消息的路由键，因此非常适合用于需要将同一消息分发给多个消费者的广播场景，例如系统通知、日志分发等。",
    "source": "文档中「RabbitMQ概述」部分的「1.2 RabbitMQ 的工作原理」",
    "hint": "哪种交换机类型的作用类似于“广播”？"
  },
  {
    "question": "启用消息持久化会对RabbitMQ系统产生什么主要影响？",
    "options": [
      "显著降低网络延迟。",
      "简化消费者的业务逻辑代码。",
      "提高消息的可靠性，但会因磁盘I/O操作而带来性能开销，降低吞吐量。",
      "减少RabbitMQ服务器的内存占用。"
    ],
    "correctAnswerIndex": 2,
    "explanation": "消息持久化意味着RabbitMQ需要将消息写入磁盘，这是一个比内存操作慢得多的过程。虽然这样做可以极大地提高消息的可靠性，确保在服务器重启或崩溃后数据不丢失，但频繁的磁盘I/O会成为性能瓶颈，导致消息的吞吐量下降和处理延迟增加。因此，是否启用持久化需要在系统的可靠性要求和性能要求之间做出权衡。",
    "source": "文档中「RabbitMQ消息持久化」部分的「4 消息持久化与性能的权衡」",
    "hint": "思考一下，将数据写入磁盘与写入内存相比，哪个更快？这会对系统产生什么影响？"
  }
];
        console.log("Quiz Data:", JSON.parse(JSON.stringify(quizData))); // 添加这行用于调试，以可展开的JSON格式输出
        
        let currentQuestionIndex = 0;
        let score = 0;
        // 存储每个问题的回答状态
        const userAnswers = new Array(quizData.length).fill(null); 

        const questionTextEl = document.getElementById('question-text');
        const optionsListEl = document.getElementById('options-list');
        const resultContainerEl = document.getElementById('result-container');
        const quizContentEl = document.getElementById('quiz-content');
        const progressIndicatorEl = document.getElementById('progress-indicator');
        const prevBtn = document.getElementById('prev-btn');
        const nextBtn = document.getElementById('next-btn');
        const hintBtn = document.getElementById('hint-btn');
        const hintContainerEl = document.getElementById('hint-container');

        function loadQuestion() {
          resultContainerEl.innerHTML = '';
          optionsListEl.innerHTML = '';
          hintContainerEl.style.display = 'none'; // 隐藏提示
          
          if (currentQuestionIndex >= quizData.length) {
            showFinalScore();
            return;
          }

          updateProgress();

          const currentQuestion = quizData[currentQuestionIndex];
          questionTextEl.textContent = `(${currentQuestionIndex + 1}/${quizData.length}) ${currentQuestion.question}`;
          
          currentQuestion.options.forEach((optionText, index) => {
            const li = document.createElement('li');
            li.className = 'option-item';
            li.textContent = optionText;
            li.dataset.index = index; // Store index in a data attribute
            // 如果这道题已经回答过，恢复状态
            if (userAnswers[currentQuestionIndex] !== null) {
                if (index === userAnswers[currentQuestionIndex]) {
                    li.classList.add('selected');
                }
            }
            optionsListEl.appendChild(li);
          });

          // 如果已经回答过，直接显示结果
          if (userAnswers[currentQuestionIndex] !== null) {
              const isCorrect = userAnswers[currentQuestionIndex] === currentQuestion.correctAnswerIndex;
              showResult(isCorrect, currentQuestion);
          }
          
          updateNavigationButtons();
          updateProgress();
        }

        function selectOption(optionIndex) {
            userAnswers[currentQuestionIndex] = optionIndex;
            const currentQuestion = quizData[currentQuestionIndex];
            const isCorrect = optionIndex === currentQuestion.correctAnswerIndex;

            // 重新计算分数
            score = userAnswers.reduce((acc, answer, index) => {
                return answer === quizData[index].correctAnswerIndex ? acc + 1 : acc;
            }, 0);

            showResult(isCorrect, currentQuestion);
            updateNavigationButtons();
        }
        
        function updateProgress() {
            const answeredQuestions = userAnswers.filter(answer => answer !== null).length;
            const progressPercentage = (answeredQuestions / quizData.length) * 100;
            progressIndicatorEl.style.width = `${progressPercentage}%`;
        }
        
        function updateNavigationButtons() {
            prevBtn.style.display = 'block';
            nextBtn.style.display = 'block';
            hintBtn.style.display = 'block'; // 显示提示按钮

            prevBtn.disabled = currentQuestionIndex === 0;
            nextBtn.disabled = false; // 最后一题时，下一题按钮不禁用，而是用于显示报告
            nextBtn.textContent = (currentQuestionIndex === quizData.length - 1) ? '查看报告' : '下一题';
            
            // 如果当前问题没有提示，则禁用提示按钮并隐藏提示内容
            if (!quizData[currentQuestionIndex].hint) {
                hintBtn.disabled = true;
                hintContainerEl.style.display = 'none';
                hintContainerEl.textContent = ''; // 清除旧的提示内容
            } else {
                hintBtn.disabled = false;
            }
        }

        function showResult(isCorrect, questionData) {
            resultContainerEl.innerHTML = ''; // 清空之前的结果
            const resultBox = document.createElement('div');
            resultBox.className = `result-box ${isCorrect ? 'correct' : 'incorrect'}`;
            
            let html = `<h3>${isCorrect ? '回答正确！' : '回答错误'}</h3>`;
            if (!isCorrect) {
                html += `<p><strong>正确答案是：</strong> ${questionData.options[questionData.correctAnswerIndex]}</p>`;
            }
            html += `<div class="explanation-text">${questionData.explanation}</div>`;
            html += `<div class="source-text">来源: ${questionData.source}</div>`;
            
            resultBox.innerHTML = html;
            resultContainerEl.appendChild(resultBox);

            // 禁用所有选项的点击事件，并高亮正确/错误答案
            Array.from(optionsListEl.children).forEach((child, index) => {
                child.style.pointerEvents = 'none';
                // 高亮正确答案
                if (index === questionData.correctAnswerIndex) {
                    child.classList.add('correct'); // 需要添加CSS样式
                    child.style.backgroundColor = '#d4edda';
                    child.style.borderColor = '#c3e6cb';
                }
                // 如果选错了，高亮错误选项
                if (!isCorrect && index === userAnswers[currentQuestionIndex]) {
                    child.classList.add('incorrect'); // 需要添加CSS样式
                    child.style.backgroundColor = '#f8d7da';
                    child.style.borderColor = '#f5c6cb';
                }
            });
        }

        function goToNextQuestion() {
            if (currentQuestionIndex < quizData.length - 1) {
                currentQuestionIndex++;
                loadQuestion();
            } else {
                showFinalScore();
            }
        }

        function goToPreviousQuestion() {
            if (currentQuestionIndex > 0) {
                currentQuestionIndex--;
                loadQuestion();
            }
        }
        
        function showHint() {
            const currentQuestion = quizData[currentQuestionIndex];
            if (currentQuestion.hint) {
                hintContainerEl.textContent = currentQuestion.hint;
                hintContainerEl.style.display = 'block';
            } else {
                hintContainerEl.style.display = 'none';
            }
        }

        function showFinalScore() {
            document.querySelector('.quiz-body').style.display = 'none';
            document.getElementById('quiz-footer').style.display = 'none';

            const correctCount = score;
            const totalQuestions = quizData.length;
            const answeredCount = userAnswers.filter(a => a !== null).length;
            const wrongCount = answeredCount - correctCount;
            const skippedCount = totalQuestions - answeredCount;
            const accuracy = totalQuestions > 0 ? Math.round((correctCount / totalQuestions) * 100) : 0;
            const errorRate = totalQuestions > 0 ? Math.round((wrongCount / totalQuestions) * 100) : 0;

            const finalScoreHtml =
                '<div class="final-score-container">' +
                '<h2>答题报告</h2>' +
                '<div class="score-summary">' +
                '<div class="score-card">' +
                '<h3>得分</h3>' +
                '<p>' + correctCount + ' / ' + totalQuestions + '</p>' +
                '</div>' +
                '<div class="score-card">' +
                '<h3>正确率</h3>' +
                '<p>' + accuracy + '%</p>' +
                '</div>' +
                '<div class="score-card">' +
                '<h3>错误率</h3>' +
                '<p>' + errorRate + '%</p>' +
                '</div>' +
                '<div class="score-card score-details">' +
                '<table>' +
                '<tr><td>正确</td><td>' + correctCount + '</td></tr>' +
                '<tr><td>错误</td><td>' + wrongCount + '</td></tr>' +
                '<tr><td>未答</td><td>' + skippedCount + '</td></tr>' +
                '</table>' +
                '</div>' +
                '</div>' +
                '<div class="report-actions">' +
                '<button id="review-btn">回顾测验</button>' +
                '<button class="primary" onclick="location.reload()">再试一次</button>' +
                '</div>' +
                '</div>';

            let reportEl = document.querySelector('.final-score-container');
            if (reportEl) {
                reportEl.remove();
            }
            quizContentEl.insertAdjacentHTML('beforeend', finalScoreHtml);
            document.getElementById('review-btn').addEventListener('click', reviewQuiz);
        }

        function reviewQuiz() {
            const reportEl = document.querySelector('.final-score-container');
            if (reportEl) {
                reportEl.remove();
            }

            document.querySelector('.quiz-body').style.display = 'block';
            document.getElementById('quiz-footer').style.display = 'flex';
            
            currentQuestionIndex = 0;
            loadQuestion();
            updateNavigationButtons(); // Ensure nav buttons are correctly displayed
        }

        // Event Delegation for options
        optionsListEl.addEventListener('click', (event) => {
            if (event.target && event.target.matches('li.option-item')) {
                // Check if the question has already been answered
                if (userAnswers[currentQuestionIndex] === null) {
                    const selectedIndex = parseInt(event.target.dataset.index, 10);
                    selectOption(selectedIndex);
                }
            }
        });

        prevBtn.addEventListener('click', goToPreviousQuestion);
        nextBtn.addEventListener('click', goToNextQuestion);
        hintBtn.addEventListener('click', showHint);
        
        // 初始加载
        loadQuestion();
      </script>
    </body>
    </html>
  